package edu.wtbu.cs.androiddemo.activity;

import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;

import edu.wtbu.cs.androiddemo.MainActivity;
import edu.wtbu.cs.androiddemo.net.retrofit.GoodsService;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.List;

import edu.wtbu.cs.androiddemo.R;
import edu.wtbu.cs.androiddemo.net.GoodInfo;
import edu.wtbu.cs.androiddemo.net.GoodsListAdapter;

import  edu.wtbu.cs.androiddemo.net.AccessToServer;
import edu.wtbu.cs.androiddemo.net.JsonUtil;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * 通过HttpURLConnection 获取商品列表数据
 * 在通过RecylerView渲染到界面
 *
 *  mark Android高版本联网失败报错:Cleartext HTTP traffic to xxx not permitted解决方法
 *  https://blog.csdn.net/gengkui9897/article/details/82863966
 */
public class HttpUrlConSampleActivity extends AppCompatActivity {

    public static String logTag = HttpUrlConSampleActivity.class.getName();

    private LinearLayoutManager linearLayoutManager;
    private RecyclerView recyclerView;
    private Handler mHandler;

    //模拟器访问宿主机JTM后端服务 使用IP：10.0.2.2
    private String url="http://10.0.2.2:8080/HappyShop/shopSer";

    private String url2="http://10.0.2.2:8080/HappyShop/shopSer?keyword=1";

    private List<GoodInfo> goodInfos;

    Runnable updataUi = new Runnable() {
        @Override
        public void run() {
            linearLayoutManager = new LinearLayoutManager(HttpUrlConSampleActivity.this);
            recyclerView.setLayoutManager(linearLayoutManager);
            //为recycleViews设定动画
            recyclerView.setItemAnimator(new DefaultItemAnimator());
            //为recycleViews添加分割线
            recyclerView.addItemDecoration(new DividerItemDecoration(HttpUrlConSampleActivity.this,
                    DividerItemDecoration.VERTICAL));
            Gson gson = new Gson();
            Log.i("listData", gson.toJson(goodInfos));
            System.out.println(gson.toJson(goodInfos));
            recyclerView.setAdapter(new GoodsListAdapter(HttpUrlConSampleActivity.this, goodInfos));
        }
    };



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_http_url_con_sample);
        recyclerView =  findViewById(R.id.recycle_Viewes);
        String userOkHttp = getIntent().getStringExtra("userOkHttp");
        if (userOkHttp.equals("1")){
            getData(url2);
        }else if (userOkHttp.equals("0")){
            getDataFromSever();
        }else {
            getDataByRetrofit();
        }
    }

    /**
     * 通过使用Retrofit框架 进行网络请求
     */
    public void getDataByRetrofit(){
        Log.i(logTag,"【Retrofit】get Goods Data By Retrofit");
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://10.0.2.2:8080/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        GoodsService service = retrofit.create(GoodsService.class);
        retrofit2.Call<List<GoodInfo>>  listCall =service.getGoodsByKeyWord2("1");
        listCall.enqueue(new retrofit2.Callback<List<GoodInfo>>() {
           @Override
           public void onResponse(retrofit2.Call<List<GoodInfo>> call, retrofit2.Response<List<GoodInfo>> response) {
               Log.i(logTag,response.toString());
               if(response.isSuccessful()){
                   goodInfos=response.body();
                   HttpUrlConSampleActivity.this.runOnUiThread(updataUi);
               }
           }
           @Override
           public void onFailure(retrofit2.Call<List<GoodInfo>> call, Throwable t) {
               Toast.makeText(HttpUrlConSampleActivity.this,"获取数据失败",Toast.LENGTH_LONG).show();

           }
       });

    }
    public void getDataFromSever() {
        Log.i(logTag,"【HttpURLConnection】get Goods Data By HttpURLConnection");
        new Thread() {
            public void run() {// 线程执行体
                String response= AccessToServer.doGet(url,new String[] {"keyword"}, new String[] {"1"});
                goodInfos= JsonUtil.getInstance().jsonToArrayList(response, GoodInfo.class);
                HttpUrlConSampleActivity.this.runOnUiThread(updataUi);
            }
        }.start();
    }


    public void getData(String url) {
        Log.i(logTag,"【OkHttp】get Goods Data By OkHttp");
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Call call = client.newCall(request);
//        try {
//           Response response = call.execute();
//           if (response.isSuccessful()){
//               String result = response.body().string();
//               goodInfos= JsonUtil.getInstance().jsonToArrayList(result, GoodInfo.class);
//               runOnUiThread(updataUi);
//           }
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Toast.makeText(HttpUrlConSampleActivity.this,"获取数据失败",Toast.LENGTH_LONG).show();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response.isSuccessful()){
                    String result = response.body().string();
                    Log.i(logTag,result.toString());
                    goodInfos= JsonUtil.getInstance().jsonToArrayList(result, GoodInfo.class);
                    if (goodInfos != null) {
                        runOnUiThread(updataUi);
                    }
                }
            }
        });
    }
}